package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.example.dao.SysStoreDao;
import com.example.dto.Oauth2RegisteredClientDTO;
import com.example.dto.Oauth2RegisteredClientQueryDTO;
import com.example.dto.SysStoreDTO;
import com.example.entity.Oauth2RegisteredClientEntity;
import com.example.entity.SysStoreClientsEntity;
import com.example.entity.SysStoreEntity;
import com.example.excel.SysStoreExcel;
import com.example.service.Oauth2RegisteredClientService;
import com.example.service.SysStoreService;

import com.example.model.api.Result;
import com.example.model.page.PageData;
import com.example.utils.ConvertUtils;
import com.example.validator.AssertUtils;
import com.example.validator.ValidatorUtils;
import com.example.validator.group.AddGroup;
import com.example.validator.group.DefaultGroup;
import com.example.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import jakarta.servlet.http.HttpServletResponse;
import com.example.utils.ExcelUtils;

/**
* 租户门店表
*
* @author yyyyjinying 1020066395@qq.com
* @since 1.0-SNAPSHOT 2025-04-19
*/
@RestController
@RequestMapping("sysstore")
@Tag(name = "租户门店表")
public class SysStoreController {
    @Autowired
    private SysStoreService sysStoreService;

    @Autowired
    private SysStoreDao sysStoreDao;

    @Autowired
    private Oauth2RegisteredClientService oauth2RegisteredClientService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @RequestMapping(value = "page", method = {RequestMethod.POST, RequestMethod.GET})
    @PreAuthorize("hasAuthority('sys:sysstore:page')")
    public Result<PageData<SysStoreDTO>> page(@RequestParam Map<String, Object> params){
        PageData<SysStoreDTO> page = sysStoreService.page(params);

        return new Result<PageData<SysStoreDTO>>().ok(page);
    }

    @GetMapping("list") // baseService.get("/sys/sysstore/list", {})
    @Operation(summary = "列表")
    @PreAuthorize("hasAuthority('sys:sysstore:page')")
    public Result<List<SysStoreDTO>> list(@RequestParam Map<String, Object> params) {
        List<SysStoreDTO> list = sysStoreService.list(params);
        return new Result<List<SysStoreDTO>>().ok(list);
    }

    @GetMapping("undistributedlist")
    @Operation(summary = "没有分配tenantId的列表")
    @PreAuthorize("hasAuthority('sys:sysstore:page')")
    public Result<List<SysStoreDTO>> undistributedlist(@RequestParam Map<String, Object> params) {
        Object tenantId = params.get("tenantId");
        List<SysStoreEntity> list = sysStoreService.undistributedlist(tenantId == null ? null : Long.valueOf(tenantId.toString()));
        return new Result<List<SysStoreDTO>>().ok(ConvertUtils.sourceToTarget(list, SysStoreDTO.class));
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @PreAuthorize("hasAuthority('sys:sysstore:info')")
    public Result<SysStoreDTO> get(@PathVariable("id") Long id){
        SysStoreDTO data = sysStoreService.get(id);
        List<SysStoreClientsEntity> sysStoreClients = sysStoreDao.selectClientByStoreId(id);
        List<String> sysStoreClientsList = sysStoreClients.stream().map(SysStoreClientsEntity::getClientId).toList();
        data.setClientPrimaryIds(sysStoreClientsList);
        return new Result<SysStoreDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @PreAuthorize("hasAuthority('sys:sysstore:save')")
    public Result<String> save(@RequestBody SysStoreDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysStoreService.save(dto);



        return new Result<String>().ok("ok");
    }

    @PutMapping
    @Operation(summary = "修改")
    @PreAuthorize("hasAuthority('sys:sysstore:update')")
    public Result<String> update(@RequestBody SysStoreDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysStoreService.update(dto);
        sysStoreDao.deleteByStoreIdAndClientIds(List.of(dto.getStoreId()));
        List<String> clientPrimaryIds = dto.getClientPrimaryIds();
        if (CollectionUtil.isNotEmpty(clientPrimaryIds)) {
            List<SysStoreClientsEntity> collect = clientPrimaryIds.stream().map(clientPrimaryId -> {
                return new SysStoreClientsEntity(dto.getStoreId(), clientPrimaryId);
            }).toList();
            sysStoreDao.batchInsertClientIdStoreId(collect);
        }
        return new Result<String>().ok("ok");
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @PreAuthorize("hasAuthority('sys:sysstore:delete')")
    public Result<String> delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        sysStoreService.delete(ids);
        sysStoreDao.deleteByStoreIdAndClientIds(List.of(ids));
        return new Result<String>().ok("ok");
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @PreAuthorize("hasAuthority('sys:sysstore:export')")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysStoreDTO> list = sysStoreService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "租户门店表", list, SysStoreExcel.class);
    }

}